<template>
  <el-dialog
    v-model="visible"
    :title="props.title || '影像资料'"
    :width="props.width || '1200px'"
    align-center
    destroy-on-close
  >
    <div class="imaging-data-content">
      <div class="search-bar">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :clearable="true"
        />
        <el-select
          v-model="searchParams.medicalType"
          placeholder="检查类型"
          clearable
          style="width: 220px"
        >
          <el-option
            v-for="item in medicalTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="handleUpload(null, '1')"
          >上传影像</el-button
        >
      </div>

      <div v-if="loading" class="loading-wrapper">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else>
        <el-table
          v-loading="loading"
          :data="tableData"
          class="table-container"
          style="width: 100%"
          border
        >
          <el-table-column prop="checkItem" label="检查项目" width="150" />
          <el-table-column label="影像二维码" min-width="200">
            <template #default="scope">
              <div class="image-url-cell">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleUpload(scope.row, '2')"
                >
                  上传二维码
                </el-button>
                <div v-if="scope.row.qrcodeImageList.length > 0">
                  <el-image
                    v-for="(url, idx) in scope.row.qrcodeImageList"
                    :key="idx"
                    :src="url"
                    fit="contain"
                    style="width: 50px; height: 50px"
                    @click="handlePreview(url)"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="影像胶片" width="400">
            <template #default="scope">
              <div class="image-film-cell">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleUpload(scope.row, '1')"
                >
                  上传影像图片
                </el-button>
                <!-- 循环展示 materialUrlList 中的每个图片，便于查看所有影像胶片 -->
                <div
                  v-if="
                    scope.row.materialUrlList &&
                    scope.row.materialUrlList.length > 0
                  "
                  style="display: flex; flex-wrap: wrap"
                >
                  <el-image
                    v-for="(url, idx) in scope.row.materialUrlList"
                    :key="idx"
                    :src="url"
                    fit="contain"
                    :style="{
                      width: '50px',
                      height: '50px',
                      marginRight: '4px',
                      position: 'relative',
                      zIndex: 9999
                    }"
                  />
                  <!--      :preview-src-list="scope.row.materialUrlList" -->
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchParams.pageNum"
            v-model:page-size="searchParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
    <!-- <UploadImg
      ref="uploadRef"
      :title="'上传影像'"
      :accept="'image/png, image/jpeg, image/jpg'"
      :show-tip="true"
      :multiple="false"
      :limit="1"
      @update:modelValue="handleUploadSuccess"
    /> -->

    <UploadComponent
      ref="uploadRef"
      :multiple="false"
      :limit="10"
      :max-size="15"
      :isFrom="isFrom"
      extensions=".jpg,.jpeg,.png"
      :tips="['支持 jpg、jpeg、png 格式', '上传的影像资料将用于医疗诊断参考']"
      :upload-api="handleUploadDocument"
      :imageTypeChoose="imageTypeChoose"
      :checkItemIdChoose="checkItemIdChoose"
      @success="(data: any) => handleUploadSuccess(data)"
      @cancel="handleUploadCancel"
    />
  </el-dialog>

  <!-- 图片预览弹窗 -->
  <el-dialog
    v-model="previewVisible"
    title="图片预览"
    width="800px"
    align-center
    destroy-on-close
    :show-close="true"
    class="image-preview-dialog"
  >
    <div class="preview-container">
      <el-image
        :src="previewImageUrl"
        class="preview-image"
        :preview-src-list="[previewImageUrl]"
        :initial-index="0"
      />
    </div>
    <template #footer>
      <div class="preview-footer">
        <el-button @click="handleClosePreview">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reportApi } from "@/api/report-api";
import { useToolsStore } from "@/store/modules/tools";
import { ElMessage } from "element-plus";
import { computed, reactive, ref } from "vue";
// import UploadImg from "../uploadImg/index1.vue";
import UploadComponent from "@/components/Upload/index.vue";

const toolsStore = useToolsStore();
const dictData = computed(() => toolsStore.getDictData());
const medicalTypeList = computed(() => dictData.value.medicalTypeList);
// 定义接口类型
interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
  dataType: number;
  requestId: string;
}

interface ImageListResponse {
  pageNum: number;
  pageSize: number;
  total: number;
  pages: number;
  list: ImageItem[];
  emptyFlag: boolean;
}

interface ImageItem {
  reportImageId: number;
  checkCode: string;
  checkType: string;
  checkItem: string;
  checkDate: string;
  imageUrl: string;
  imageFilm: string;
}

// 定义组件属性
const props = defineProps<{
  // reportId?: string;
  title?: string;
  width?: string | number;
}>();

// 定义事件
const emit = defineEmits(["update:reportId"]);

// 响应式数据
const visible = ref(false);
const loading = ref(false);
const tableData = ref<ImageItem[]>([]);
const total = ref(0);
const dateRange = ref<[string, string] | null>(null);
const isFrom = ref("reportImage");
// 当前选中的影像id
const reportImageId = ref(0);
const imageTypeChoose = ref("1");
const checkItemIdChoose = ref(null);
// 图片预览相关
const previewVisible = ref(false);
const previewImageUrl = ref("");

// 搜索参数
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  healthReportId: "",
  medicalType: "",
  startDate: "",
  endDate: ""
});

// 查询影像列表
const handleQueryImageList = async () => {
  // 确保有 healthReportId 时才调用接口
  if (!searchParams.healthReportId) {
    console.log("缺少必要的 healthReportId 参数");
    return;
  }

  loading.value = true;
  try {
    const res = (await reportApi.queryImageList(
      searchParams
    )) as ApiResponse<ImageListResponse>;
    if (res.code === 0 && res.data) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || "获取影像资料失败");
    }
  } catch (error) {
    console.error("获取影像资料失败:", error);
    ElMessage.error("获取影像资料失败");
  } finally {
    loading.value = false;
  }
};

// 自定义上传API函数
const handleUploadDocument = async (file: File, config?: any) => {
  try {
    // 准备预签名URL的请求参数
    const params = {
      fileName: file.name,
      fileType: 3
    };

    // 获取预签名URL
    const presignedResponse = await reportApi.presignedApi(params);

    if (presignedResponse?.data?.presignedUrl) {
      // 第二步：使用fetch直接上传到预签名URL
      const uploadResponse = await fetch(
        presignedResponse?.data?.presignedUrl,
        {
          method: "PUT",
          body: file,
          headers: {
            "Content-Type": file?.type || "application/octet-stream"
          }
        }
      );
      // 构建传递给handleUploadSuccess的数据，包含配置参数
      const successData: any = {
        resourceKey: presignedResponse?.data.objectKey
      };

      if (config?.checkItem) {
        successData.checkItem = +config.checkItem;
      }
      if (config?.imageType) {
        successData.imageType = +config.imageType;
      }

      handleUploadSuccess(successData);
      return uploadResponse.body;
    }
  } catch (error) {
    console.error("文档上传失败:", error);
    throw error;
  }
};

const handleUploadCancel = () => {};

// 搜索处理
const handleSearch = () => {
  if (dateRange.value) {
    searchParams.startDate = dateRange.value[0];
    searchParams.endDate = dateRange.value[1];
  } else {
    searchParams.startDate = "";
    searchParams.endDate = "";
  }
  searchParams.pageNum = 1;
  handleQueryImageList();
};

// 分页处理
const handleSizeChange = (val: number) => {
  searchParams.pageSize = val;
  handleQueryImageList();
};

const handleCurrentChange = (val: number) => {
  searchParams.pageNum = val;
  handleQueryImageList();
};

// 上传影像
const uploadRef = ref();
const handleUpload = (row: any, imageType: string) => {
  isFrom.value = "reportImage";
  uploadRef.value?.open("image");
  console.log("imageType", imageType, row);
  imageTypeChoose.value = imageType;
  if (row?.checkItemId) {
    checkItemIdChoose.value = row.checkItemId;
  } else {
    checkItemIdChoose.value = "";
  }
};
const handleUploadFilm = (row: any) => {
  reportImageId.value = row.reportImageId;
  uploadRef.value?.open("film");
  isFrom.value = "film";
};

// 处理上传成功
const handleUploadSuccess = async (data: any) => {
  console.log("%c mujin 0000", "color: red", data, isFrom.value);
  if (data.resourceKey && isFrom.value == "film") {
    // 优化判断条件：只要 reportImageId.value 不为 0、undefined、null、空字符串都视为有效
    if (
      reportImageId.value !== 0 &&
      reportImageId.value !== undefined &&
      reportImageId.value !== null
    ) {
      try {
        const res = await reportApi.uploadImageFilm({
          reportImageId: reportImageId.value,
          resourceKeyList: [data.resourceKey],
          imageType: data.imageType
        });
        console.log("影像胶片上传结果：", res);
      } catch (error) {
        console.error("影像胶片上传失败：", error);
        ElMessage.error("影像胶片上传失败，请重试");
        return;
      }
    }
    handleQueryImageList(); // 刷新列表
  } else if (data.resourceKey && isFrom.value == "reportImage") {
    try {
      // 构建上传参数，包含从Upload组件传来的checkItem和imageType
      const uploadParams: any = {
        reportId: searchParams.healthReportId,
        resourceKeyList: [data.resourceKey]
      };

      // 如果有checkItem参数，使用它作为checkType
      if (data.checkItem) {
        uploadParams.checkItem = +data.checkItem || 1;
      } else {
        ElMessage.error("请选择检查项目");
        return;
      }

      // 如果有imageType参数，添加到请求中
      if (data.imageType) {
        uploadParams.imageType = +data.imageType;
      } else {
        ElMessage.error("请选择影像类型");
        return;
      }

      console.log("最终上传参数：", uploadParams);

      const res = await reportApi.uploadImage(uploadParams);
      console.log("影像资料上传结果：", res);
    } catch (error) {
      console.error("影像资料上传失败：", error);
      ElMessage.error("影像资料上传失败，请重试");
      return;
    }
    handleQueryImageList(); // 刷新列表
  }
};

// 打开弹窗
const open = async (reportId: string) => {
  visible.value = true;
  searchParams.healthReportId = reportId;
  handleQueryImageList();
};

// 图片预览处理
const handlePreview = (url: string) => {
  console.log("预览图片URL:", url);
  previewImageUrl.value = url;
  previewVisible.value = true;
};

// 关闭图片预览
const handleClosePreview = () => {
  previewVisible.value = false;
  previewImageUrl.value = "";
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
  tableData.value = [];
  dateRange.value = null;
  searchParams.medicalType = "";
  searchParams.startDate = "";
  searchParams.endDate = "";
  searchParams.pageNum = 1;
  emit("update:reportId", undefined);
};

// 对外暴露方法
defineExpose({
  open
});
</script>

<style lang="scss" scoped>
.imaging-data-content {
  min-height: 400px;
  padding: 16px;

  .search-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    align-items: center;
  }

  .loading-wrapper {
    padding: 20px;
  }

  .image-url-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .table-container {
    .el-table th.el-table__cell {
      background-color: #f5f5f5;
    }
  }
}
.image-film-cell {
  display: flex;
  align-items: center;
  flex-direction: row;
  gap: 3px;
}

// 图片预览弹窗样式
.image-preview-dialog {
  .preview-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;

    .preview-image {
      max-width: 600px;
      max-height: 100%;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }

  .preview-footer {
    display: flex;
    justify-content: center;
    padding: 10px 0;
  }
}
</style>
